import api from '@/core/Api'
import {Products} from '@/router/urls'

class Service {
  async getPage (params) {
    try {
      let res = await api.aget(Products.getPage(), {
        data: params
      })
      // console.log(res)
      if (res.data.code === 0) {
        return res.data.data
      }
    } catch (e) {
      console.log(e)
    }
    return []
  }
  grant (values) {
    return api.post(Products.grant(values.get('id')), values)
  }
  save (values) {
    return values.id ? api.put(Products.update(values.id), values) : api.post(Products.save(), values)
  }
  delete (id) {
    return api.post(Products.delete(id), {
      _method: 'delete'
    })
  }
  async getTree (id) {
    try {
      let res = await api.aget(Products.getTree(id))
      // console.log(res)
      if (res.data.code === 0) {
        var nodeMap = {}
        var nodes = []

        for (let node of res.data.data) {
          var newNode = {
            key: node.id,
            pid: node.pid,
            value: node.id,
            title: node.name,
            checked: node.checked
          }
          if (!node.pid) {
            nodes.push(newNode)
          } else {
            var p = nodeMap[node.pid]
            if (p) {
              if (p.children) {
                p.children.push(newNode)
              } else {
                p.children = [newNode]
              }
              p.open = true // 展开节点
            } else {
              nodes.push(newNode)
            }
          }
          nodeMap[node.id] = newNode
        }
        return nodes
      }
    } catch (e) {
      console.log(e)
    }
    return []
  }
}

export default new Service()
